package com.yitong.equipment.base

import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.Nullable
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.viewModelScope
import com.gyf.immersionbar.components.SimpleImmersionOwner
import com.yitong.equipment.entity.other.Event
import com.yitong.equipment.utils.ClassUtil
import com.yitong.equipment.utils.EventBusUtil
import kotlinx.coroutines.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

abstract class BaseFragment<VM : AndroidViewModel, SV : ViewDataBinding> : Fragment() {
    protected lateinit var viewModel: VM
    protected lateinit var bindingView: SV

    private var isFirstLoad = true
    private var activity: Activity? = null

    override fun onAttach(context: Context) {
        super.onAttach(context)
        activity = context as Activity
    }

    @Nullable
    override fun onCreateView(inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?): View? {
        if (isRegisterEventBus()) {
            EventBusUtil.register(this)
        }
        bindingView = DataBindingUtil.inflate<SV>(activity?.layoutInflater!!, setContent(), null, false)
        return bindingView.root
    }

    override fun onResume() {
        super.onResume()
        if (isFirstLoad) {
            initViewModel()
            initView()
            initData()
            firstLoad()
            isFirstLoad = false
        }else {
            notFirstLoad()
        }
    }


    /**
     * 做初始化UI相关操作 比如RecyclerView设置方向等
     */
    protected open fun initView() {}

    /**
     * 做初始化数据 比如获取其他页面数据 初始化页面数据相关操作
     */
    protected open fun initData() {}

    /**
     * fragment第一次数据加载初始化
     */
    protected open fun firstLoad() {}
    /**
     * fragment非第一次 比如从其他页面切换回来 需要做某些操作
     */
    protected open fun notFirstLoad() {}

    /**
     * 初始化ViewModel
     */
    private fun initViewModel() {
        val viewModelClass = ClassUtil.getViewModel<VM>(this)
        if (viewModelClass != null) {
            viewModel = activity?.application?.let {
                ViewModelProvider.AndroidViewModelFactory(it).create(viewModelClass)
            }!!
        }
    }

    protected open fun <T : View?> getView(id: Int): T {
        return view?.findViewById<View>(id) as T
    }

    /**
     * 布局
     */
    abstract fun setContent(): Int


    /**
     * 是否注册事件分发
     *
     * @return true绑定EventBus事件分发，默认不绑定，子类需要绑定的话复写此方法返回true.
     */
    open fun isRegisterEventBus(): Boolean {
        return false
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventBusCome(event: Event<Any>?) {
        if (event != null) {
            receiveEvent(event)
        }
    }

    /**
     * 接收到分发到事件
     *
     * @param event 事件
     */
    open fun receiveEvent(event: Event<Any>) {

    }

    override fun onDestroyView() {
        super.onDestroyView()
        if (isRegisterEventBus()) {
            EventBusUtil.unregister(this)
        }
    }

    fun launch(isMain:Boolean  = false, block: suspend CoroutineScope.() -> Unit): Job {
        return lifecycleScope.launch {
            withContext(if (isMain) Dispatchers.Main else Dispatchers.IO) {
                block.invoke(this)
            }
        }
    }
}